package org.example.shop.service;

import org.example.shop.entity.User;
import org.example.shop.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    // 检查用户名是否已存在
    public boolean isAccountExists(String account) {
        return userMapper.isAccountExists(account) > 0;
    }

    public boolean insertUser(String account, String password, String email, String telphone) {
        if (isAccountExists(account)) {
            return false; // 用户名已存在，返回 false
        }

        User user = new User();
        user.setAccount(account);
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setEmail(email);
        user.setTelphone(telphone);
        user.setPoints(0);
        user.setMoney(BigDecimal.valueOf(0.0));
        user.setRegTime(LocalDateTime.now());
        user.setStatus("Y");
        user.setAvatar("");
        int re = userMapper.insertUser(user);
        return re > 0;
    }
    public User validateUser(String account, String password) {
        User user = userMapper.selectByAccount(account);
        if (user == null) return null;
        String encryptedPwd = DigestUtils.md5DigestAsHex(password.getBytes());
        return encryptedPwd.equals(user.getPassword()) ? user : null;
    }
}